package com.wsx.ones.akka.service.impl;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import com.wsx.ones.akka.domian.AkkaRequest;
import com.wsx.ones.akka.domian.Data;
import com.wsx.ones.akka.domian.Message;
import com.wsx.ones.akka.service.AkkaService;
import com.wsx.ones.boots.akka.SpringExtension;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @author wangshuaixin
 * @Title: com.wsx.ones.akka.service.impl.AkkaServiceImpl
 * @Description: TODO
 * @date 2019/05/10
 */
@Component
public class AkkaServiceImpl implements AkkaService {


    private ActorSystem actorSystem;

    private SpringExtension springExtension;

    public AkkaServiceImpl(ActorSystem actorSystem, SpringExtension springExtension) {
        this.actorSystem = actorSystem;
        this.springExtension = springExtension;
    }


    @Override
    public CompletableFuture<Message> async(String actorName, int num) {
        CompletableFuture<Message> future = new CompletableFuture<Message>();
        ActorRef work = actorSystem.actorOf(springExtension.prop("workActor", future), "work-actor");
        work.tell(new Message(num, actorName), null);
        return future;
    }


    @Override
    public Data actor(AkkaRequest request) {
        Data data = new Data(request.getName(), request.getDate().getTime());
        CompletableFuture<Message> future = new CompletableFuture<Message>();
        ActorRef work = actorSystem.actorOf(springExtension.prop("workActor", future), "work-actor");
        work.tell(data, null);

        try {
            data.setResult(future.get().getResult());
        } catch (Exception e) {
            data.setResult(e.getMessage());
        }

        return data;
    }
}
